package com.wxm.api.xml;

import com.wxm.api.exception.CrawlerException;
import com.wxm.jsoup.util.JsoupUtils;
import lombok.Getter;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *      爬虫xml容器类
 * </p>
 *
 * @author wxm
 * @Date 2021/9/29
 */
@Getter
public class CrawlerContainer extends Container{
    @Override
    protected void fillAttribute(org.dom4j.Element element) {}

    @Override
    protected void judgeAttributeNull() {
        if (this.clazz == null)CrawlerException.error("缺失属性 clazz");
    }

    @Override
    public Object fillHtmlObject(org.jsoup.nodes.Element element, Object o) {
        String[] selectSplit = new String[]{};
        String[] indexSplit = new String[]{};
        if (this.select != null)selectSplit = this.select.split(";");
        if (this.index != null)indexSplit = this.index.split(";");

        if (selectSplit.length != indexSplit.length){
            CrawlerException.error("请检查select和index的值[长度不一致] " + this.select + "/" + this.index);
        }

        if (this.collection){
            //集合类型
            Elements es = JsoupUtils.getElementIndexs(element, selectSplit, indexSplit);
            List<Object> list = new ArrayList<>(es.size());
            for (org.jsoup.nodes.Element e : es) {
                try {
                    o = this.clazz.newInstance();
                } catch (Exception exception) {
                    CrawlerException.error("初始化clazz失败 ：" +  this.clazz);
                    exception.printStackTrace();
                }
                for (CrawlerFiledContainer child : this.children) {
                    child.fillHtmlObject(e,o);
                }
                list.add(o);
            }
            return list;
        }else {
            //普通对象类型
            org.jsoup.nodes.Element e = JsoupUtils.getElementIndex(element, selectSplit, indexSplit,true);
            try {
                o = this.clazz.newInstance();
            } catch (Exception exception) {
                CrawlerException.error("初始化clazz失败 ：" +  this.clazz);
                exception.printStackTrace();
            }
            for (CrawlerFiledContainer child : this.children) {
                child.fillHtmlObject(e,o);
            }
            return o;
        }
    }
}
